/**
 * @class UI-基础件-右侧栏
 * @author DuskyHuang 圣子
 * @description 包含行星磁场、半径、自转轴、天文面等控制按钮
*/

import { _decorator, Node, Toggle, Sprite } from 'cc';
import { Mediator, TweenSwitcher } from 'cfw';
import { UI, View } from 'notifications';
import { VisitProxy, planetary, cosmos, visit } from 'proxies';
const { ccclass, property } = _decorator;

@ccclass('cocosmos.right-menu')
export class RightMenu extends Mediator {

    @property(Node) public localLine: Node = null;
    @property(Node) public btnTideLock: Node = null;
    @property(Node) public btnLunar: Node = null;
    @property(Node) public btnEquatorial: Node = null;
    @property(Node) public btnEcliptic: Node = null;
    @property(Node) public btnMagnetics: Node = null;
    @property(Node) public btnDiameter: Node = null;
    @property(Node) public btnAxis: Node = null;

    protected onLoad(): void {
        this._init();
        this._listen();
    }

    protected start(): void {
        this.localLine.active = false;
        this._initToggleEventAndStates();
    }

    protected update(): void {
        if (isNum(visit.center?.suggest)) {
            this.localLine.active = (visit.center?.suggest + VisitProxy.DETAIL_TOLERANCE) > cosmos.pow10;
        }
    }

    private _init(): void {
        this._tws = this.localLine.getComponent(TweenSwitcher);
    }

    private _listen(): void {
        this.on(Transform.ZOOM_START, this.onVisitStart);
        this.on(Transform.VISIT_OVER, this.onVisitOver);
    }

    protected onVisitStart(): void {
        this._tws.hide(true);
    }

    protected onVisitOver(): void {
        this._resetUIByScope();
        this._tws.show(true);
    }

    private _resetUIByScope(): void {
        const { inPlanet, inPlanetary, inSatellite, centerName, inType } = visit;
        this.btnAxis.active = this.btnDiameter.active = (inPlanetary && inType !== 'belts' && inType !== 'comet') || inSatellite;
        this.btnMagnetics.active = this.btnEcliptic.active = this.btnEquatorial.active = inPlanet;
        this.btnLunar.active = inPlanet && centerName === 'Earth';
        this.btnTideLock.active = false; // TODO
    }

    protected toggleInList(toggle: Toggle): void {
        const checked: boolean = toggle.isChecked;
        toggle.getComponent(Sprite).enabled = !checked;
        const name = toggle.node.name;
        const ntf = Local.AXIS.split('.').head + '.' + name;
        this.notify(ntf, checked);
    }

    private _initToggleEventAndStates(): void {
        this.localLine.getComponentsInChildren(Toggle).forEach(toggle => {
            const checked = planetary.getStateByName(toggle.node.name);
            toggle.setIsCheckedWithoutNotify(checked);
            toggle.getComponent(Sprite).enabled = !checked;
            toggle.node.on(Toggle.EventType.TOGGLE, this.toggleInList, this);
        });
    }

    private _tws: TweenSwitcher;
}

const { Transform } = View, { Local } = UI;